package com.java.gulimall.seckill.schedule;

import com.java.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author jl
 * Created on 2020/9/22
 * 定时任务
 *  1.@EnableScheduling 开启定时任务功能
 *  2.@Scheduled 开启一个定时任务
 *  3.定时任务不应该阻塞,默认是阻塞的
 *    可以使用异步任务
 *    1)@EnableAsync 开启异步任务功能
 *    2)@Async 方法异步执行
 * 解决:使用异步+定时任务来完成定时任务不阻塞的功能
 */
@Slf4j
@Component
public class SeckillSkuSchedule {
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedissonClient redissonClient;
    //秒杀商品上架功能的锁
    private final String upload_lock = "seckill:upload:lock";

    /**
     * 秒杀商品的定时上架
     *   每天凌晨3点上架最近3天需要秒杀的商品
     *   当天00:00:00 - 23:59:59
     *   明天00:00:00 - 23:59:59
     *   后天00:00:00 - 23:59:59
     */
    // 保证幂等性问题
    @Async
    @Scheduled(cron = "0 * * * * ?")
    public void hello() {
        // 1.重复上架无需处理
        log.info("=====上架秒杀商品");
        //分布式锁
        RLock lock = redissonClient.getLock(upload_lock);
        try {
            //加锁
            lock.lock();
            seckillService.upSeckillSkuLatest3Days();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
